<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>策略配置 - 后台管理</title>
  <link rel="stylesheet" href="/static/base.css">
  <link rel="stylesheet" href="/static/components.css">
  <link rel="stylesheet" href="/static/pages.css">
  <link rel="stylesheet" href="/static/admin/admin.css">
</head>
<body>
  <div class="admin-layout">
    <!-- 顶部导航 -->
    <div class="admin-header">
      <h2>策略配置</h2>
      <div>
        <button class="btn" onclick="location.href='/'">返回前台</button>
        <button class="btn" onclick="logout()">退出</button>
      </div>
    </div>

    <!-- 主体内容 -->
    <div class="admin-main">
      <!-- 左侧导航（公共组件注入） -->
      <div class="admin-sidebar"></div>

      <!-- 右侧内容区域 -->
      <div class="admin-content">
        <div class="content-page active">
          <h3>策略配置</h3>
          <p class="page-description">配置选股策略的执行参数和策略选择</p>

          <div class="content-grid">
            <div class="content-card">
              <h4>参数设置</h4>
              <div class="form-group">
                <label class="form-label">执行日期</label>
                <input type="date" id="exec-date" class="form-control">
                <div class="form-help">不设置时默认当天</div>
                <div id="trading-dates-info" class="form-help" style="margin-top: 8px; padding: 8px; background: #f8f9fa; border-radius: 4px; font-size: 0.85em;">
                  <div>最小交易日: <span id="min-date">-</span></div>
                  <div>最大交易日: <span id="max-date">-</span></div>
                  <div>交易天数: <span id="trading-days">-</span></div>
                </div>
              </div>

              <div class="form-group">
                <label class="form-label">清空执行日缓存</label>
                <label class="cache-checkbox">
                  <input type="checkbox" id="clear-cache">
                  <span class="checkmark"></span>
                  清空缓存后将强制重新执行策略
                </label>
              </div>

              <div class="form-group">
                <label class="form-label">策略搜索</label>
                <input type="text" id="strategy-search" class="form-control" placeholder="输入关键词过滤策略…" oninput="renderStrategyList()">
              </div>

              <div class="form-group">
                <label class="form-label">选择策略</label>
                <div id="strategy-list" class="strategy-list" style="max-height: 40vh; overflow:auto; border:1px solid #e9ecef; border-radius:8px; padding:8px;"></div>
                <div style="margin-top:8px; display:flex; gap:8px;">
                  <button class="btn" onclick="selectAllVisible()">全选可见</button>
                  <button class="btn" onclick="clearSelected()">清空选择</button>
                </div>
              </div>

              <div class="form-group">
                <button class="btn btn-primary" onclick="saveConfig()">保存配置</button>
                <button class="btn" style="margin-left:8px;" onclick="startSelection()">开始选股</button>
              </div>
            </div>

            <div class="content-card">
              <h4>配置预览</h4>
              <div id="preview" style="background:#f8f9fa; border:1px solid #e9ecef; border-radius:8px; padding:12px; min-height:120px;">
                暂无配置，请在左侧进行设置。
              </div>

              <h4 style="margin-top:16px;">说明</h4>
              <ul style="color:#6c757d; line-height:1.8; padding-left:18px;">
                <li>选择一个或多个策略进行组合执行。</li>
                <li>勾选"清空执行日缓存"将忽略历史缓存，重新计算。</li>
                <li>保存配置后可在执行页面按配置执行策略。</li>
              </ul>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>

  <script src="/static/admin/components/sidebar.js"></script>
  <script>
    // 策略配置相关变量和函数
    let allStrategies = [];
    let selected = new Set();

    // 页面加载时初始化策略配置
    document.addEventListener('DOMContentLoaded', async function() {
      // 初始化策略配置
      const input = document.getElementById('exec-date');
      if (input) {
        input.value = new Date().toISOString().split('T')[0];
        await loadStrategies();
        loadFromStorage();
        renderStrategyList();
        renderPreview();
        
        // 加载交易日期信息
        loadTradingDatesInfo();
      }
      injectAdminSidebar('/admin/strategy-config');
    });

    // 加载策略列表
    async function loadStrategies(){
      try{
        const resp = await fetch('/api/strategies');
        const data = await resp.json();
        if(data && data.success){
          allStrategies = (data.data?.strategies || []).map(s => ({ name: s[0], desc: s[1] }));
        } else {
          allStrategies = [];
        }
      }catch(e){
        console.error('加载策略失败', e);
        allStrategies = [];
      }
    }

    // 从本地存储加载配置
    function loadFromStorage(){
      try{
        const stored = localStorage.getItem('strategy-config');
        if(stored){
          const config = JSON.parse(stored);
          selected = new Set(config.selected || []);
          if(config.exec_date) document.getElementById('exec-date').value = config.exec_date;
          if(config.clear_cache) document.getElementById('clear-cache').checked = config.clear_cache;
        }
      }catch(e){
        console.error('加载配置失败', e);
      }
    }

    // 渲染策略列表
    function renderStrategyList(){
      const container = document.getElementById('strategy-list');
      if(!container) return;
      
      const search = document.getElementById('strategy-search')?.value?.toLowerCase() || '';
      const filtered = allStrategies.filter(s => 
        s.name.toLowerCase().includes(search) || 
        (s.desc && s.desc.toLowerCase().includes(search))
      );
      
      container.innerHTML = filtered.map(s => `
        <label style="display:flex; align-items:center; gap:8px; padding:4px 0; cursor:pointer;">
          <input type="checkbox" ${selected.has(s.name) ? 'checked' : ''} 
                 onchange="toggleStrategy('${s.name}', this.checked)">
          <span style="font-weight:500;">${s.name}</span>
          ${s.desc ? `<span style="color:#6c757d; font-size:0.9em;">${s.desc}</span>` : ''}
        </label>
      `).join('');
    }

    // 切换策略选择
    function toggleStrategy(name, checked){
      if(checked) selected.add(name);
      else selected.delete(name);
      renderPreview();
    }

    // 全选可见策略
    function selectAllVisible(){
      const search = document.getElementById('strategy-search')?.value?.toLowerCase() || '';
      const filtered = allStrategies.filter(s => 
        s.name.toLowerCase().includes(search) || 
        (s.desc && s.desc.toLowerCase().includes(search))
      );
      filtered.forEach(s => selected.add(s.name));
      renderStrategyList();
      renderPreview();
    }

    // 清空选择
    function clearSelected(){
      selected.clear();
      renderStrategyList();
      renderPreview();
    }

    // 渲染预览
    function renderPreview(){
      const preview = document.getElementById('preview');
      if(!preview) return;
      
      const execDate = document.getElementById('exec-date')?.value || '';
      const clearCache = document.getElementById('clear-cache')?.checked || false;
      
      if(selected.size === 0){
        preview.innerHTML = '暂无配置，请在左侧进行设置。';
        return;
      }
      
      preview.innerHTML = `
        <div style="margin-bottom:12px;">
          <strong>执行日期:</strong> ${execDate || '当天'}
        </div>
        <div style="margin-bottom:12px;">
          <strong>清空缓存:</strong> ${clearCache ? '是' : '否'}
        </div>
        <div style="margin-bottom:12px;">
          <strong>选中策略 (${selected.size}个):</strong>
        </div>
        <div style="max-height:120px; overflow-y:auto;">
          ${Array.from(selected).map(name => `<div style="padding:2px 0;">• ${name}</div>`).join('')}
        </div>
      `;
    }

    // 保存配置
    function saveConfig(){
      const config = {
        exec_date: document.getElementById('exec-date')?.value || '',
        clear_cache: document.getElementById('clear-cache')?.checked || false,
        selected: Array.from(selected)
      };
      
      localStorage.setItem('strategy-config', JSON.stringify(config));
      alert('配置已保存');
    }

    // 开始选股
    async function startSelection(){
      if(selected.size === 0){
        alert('请至少选择一个策略');
        return;
      }
      
      const execDate = document.getElementById('exec-date')?.value || '';
      const clearCache = document.getElementById('clear-cache')?.checked || false;
      
      try{
        const response = await fetch('/api/execute-strategies', {
          method: 'POST',
          headers: {
            'Content-Type': 'application/json',
          },
          body: JSON.stringify({
            strategies: Array.from(selected),
            execution_date: execDate,
            clear_cache: clearCache
          })
        });
        
        const data = await response.json();
        if(data.success){
          alert('策略执行已启动，请查看执行记录');
        } else {
          alert('执行失败: ' + (data.error || '未知错误'));
        }
      }catch(error){
        console.error('执行策略失败:', error);
        alert('执行失败，请检查网络连接');
      }
    }

    // 加载交易日期信息
    async function loadTradingDatesInfo() {
      try {
        const response = await fetch('/admin/api/trading-dates');
        const data = await response.json();
        
        if (data.success) {
          document.getElementById('min-date').textContent = data.min_date || '-';
          document.getElementById('max-date').textContent = data.max_date || '-';
          document.getElementById('trading-days').textContent = data.trading_days || 0;
        } else {
          console.error('获取交易日期信息失败:', data.error);
          document.getElementById('min-date').textContent = '-';
          document.getElementById('max-date').textContent = '-';
          document.getElementById('trading-days').textContent = '-';
        }
      } catch (error) {
        console.error('加载交易日期信息失败:', error);
        document.getElementById('min-date').textContent = '-';
        document.getElementById('max-date').textContent = '-';
        document.getElementById('trading-days').textContent = '-';
      }
    }

    // 退出登录
    async function logout(){
      try{ 
        await fetch('/admin/logout', {method:'POST'}); 
        location.href='/admin/login'; 
      }catch(e){ 
        location.href='/admin/login'; 
      }
    }
  </script>
</body>
</html>
